package cn.lijiajia3515.cairo.starter.autoconfigure.security.oauth2.resourceserver;

import cn.lijiajia3515.cairo.security.oauth2.resource.server.web.CairoBearerTokenAuthenticationEntryPoint;
import cn.lijiajia3515.cairo.security.oauth2.resource.server.web.CairoOAuth2HttpMessageAuthenticationFailedHandler;
import cn.lijiajia3515.cairo.starter.autoconfigure.security.CairoSecurityConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;

@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(CairoSecurityConfiguration.class)
@ConditionalOnClass(value = {OAuth2ResourceServerConfigurer.class})
public class CairoOAuth2ResourceServerAutoConfiguration {

	@Bean
	BearerTokenResolver bearerTokenResolver() {
		DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
		resolver.setAllowFormEncodedBodyParameter(true);
		resolver.setAllowUriQueryParameter(true);
		return resolver;
	}

	@Bean
	@ConditionalOnMissingBean
	CairoBearerTokenAuthenticationEntryPoint cairoBearerTokenAuthenticationEntryPoint(HttpMessageConverters messageConverters) {
		return new CairoBearerTokenAuthenticationEntryPoint(messageConverters.getConverters());
	}

	@Bean
	@ConditionalOnMissingBean
	public CairoOAuth2HttpMessageAuthenticationFailedHandler cairoOAuth2AuthenticationFailedHandler(CairoBearerTokenAuthenticationEntryPoint entryPoint) {
		return new CairoOAuth2HttpMessageAuthenticationFailedHandler(entryPoint);
	}
}
